<template>
  <div class="media-report-container">
    <el-card class="search-card">
      <template #header>
        <div class="card-header">
          <span>清算收入报表查询</span>
        </div>
      </template>
      
      <el-form :model="searchForm" :inline="true">
        <el-form-item label="时间范围" required>
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            clearable
            :shortcuts="dateShortcuts"
          />
        </el-form-item>
        
        <el-form-item label="媒体">
          <el-select 
            v-model="searchForm.mediaIds" 
            placeholder="请选择媒体" 
            clearable 
            filterable 
            multiple
            collapse-tags
            collapse-tags-tooltip
            @change="handleMediaChange"
          >
            <el-option
              v-for="media in mediaOptions"
              :key="media.id"
              :label="media.name"
              :value="media.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    
    <!-- 数据表格 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>清算收入报表数据</span>
        </div>
      </template>
      
      <el-table
        v-loading="loading"
        :data="qsReportList"
        border
        style="width: 100%"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        :summary-method="getSummaries"
        show-summary
      >
        <el-table-column fixed="left" prop="incomeDate"  label="日期" width="120" />
        <el-table-column fixed="left" prop="mediaId" label="媒体ID" width="200"/>
        <el-table-column fixed="left" prop="mediaName" label="媒体名称" width="320" />
        <el-table-column prop="income" label="支出" width="200">
          <template #default="{ row }">
            {{ row.income ? (row.income / 100).toFixed(2) : '0.00' }}元
          </template>
        </el-table-column>
        <el-table-column prop="realIncome" label="收入" width="200">
          <template #default="{ row }">
            {{ row.realIncome ? (row.realIncome / 100).toFixed(2) : '0.00' }}元
          </template>
        </el-table-column>
        <el-table-column prop="profit" label="利润">
          <template #default="{ row }">
            {{ row.profit ? (row.profit / 100).toFixed(2) : '0.00' }}元
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :hide-on-single-page="false"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { fetchQsMediaIncome, type ApiQsMediaIncomeItem } from '@/api/report'
import { fetchSpaceList, type ApiSpaceItem } from '@/api/space'
import { fetchMediaList, type ApiMediaItem } from '@/api/media'

interface HotMediaItem {
  id: number
  name: string
  type: string
  views: number
  downloads: number
}

interface ReportItem {
  date: string
  totalCount: number
  newCount: number
  activeCount: number
  totalSize: number
  totalViews: number
  totalDownloads: number
  growthRate: number
}

interface SearchForm {
  dateRange: string[]
  mediaIds: string[]
}

interface MediaOption {
  id: string
  name: string
}

const loading = ref(false)
const mediaOptions = ref<MediaOption[]>([])

// 分页相关变量
const qsReportList = ref<ApiQsMediaIncomeItem[]>([])

// 加载媒体选项数据
const loadMediaOptions = async () => {
  try {
    
    const response = await fetchMediaList()
    console.log('media list:', response)
    mediaOptions.value = response.map(item => ({
      id: item.id || '',
      name: item.name || ''
    }))
  } catch (error) {
    console.error('加载媒体选项失败:', error)
  }
}

// 媒体变更处理
const handleMediaChange = (mediaIds: string[]) => {
  // 媒体变更处理逻辑
  console.log('媒体变更:', mediaIds)
}



// 获取昨天的日期范围
const getYesterdayDateRange = () => {
  const yesterday = new Date()
  yesterday.setTime(yesterday.getTime() - 3600 * 1000 * 24)
  
  const year = yesterday.getFullYear()
  const month = (yesterday.getMonth() + 1).toString().padStart(2, '0')
  const day = yesterday.getDate().toString().padStart(2, '0')
  
  const dateStr = `${year}-${month}-${day}`
  return [dateStr, dateStr] // 返回昨天的开始和结束日期（同一天）
}

const searchForm = reactive<SearchForm>({
  dateRange: getYesterdayDateRange(), // 默认选中昨天的时间范围
  mediaIds: [],
  adspaceId: ''
})

const pagination = reactive({
  currentPage: 1,
  pageSize: 31,
  total: 0
})

// 日期快捷选项
const dateShortcuts = [
  {
    text: '今天',
    value: () => {
      const today = new Date()
      const dateStr = today.getFullYear().toString() + 
                     (today.getMonth() + 1).toString().padStart(2, '0') + 
                     today.getDate().toString().padStart(2, '0')
      return [dateStr, dateStr]
    },
  },
  {
    text: '昨天',
    value: () => {
      const yesterday = new Date()
      yesterday.setTime(yesterday.getTime() - 3600 * 1000 * 24)
      const dateStr = yesterday.getFullYear().toString() + 
                     (yesterday.getMonth() + 1).toString().padStart(2, '0') + 
                     yesterday.getDate().toString().padStart(2, '0')
      return [dateStr, dateStr]
    },
  },
  {
    text: '最近7天',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 6) // 包含今天共7天
      
      const startStr = start.getFullYear().toString() + 
                       (start.getMonth() + 1).toString().padStart(2, '0') + 
                       start.getDate().toString().padStart(2, '0')
      const endStr = end.getFullYear().toString() + 
                     (end.getMonth() + 1).toString().padStart(2, '0') + 
                     end.getDate().toString().padStart(2, '0')
      return [startStr, endStr]
    },
  },
]


// 加载清算收入报表数据
const loadQsReportData = async () => {
  loading.value = true
  try {
    const params = {
      mediaIds: searchForm.mediaIds && searchForm.mediaIds.length > 0 ? searchForm.mediaIds : null,
      startDt: searchForm.dateRange && searchForm.dateRange[0] ? searchForm.dateRange[0] : null,
      endDt: searchForm.dateRange && searchForm.dateRange[1] ? searchForm.dateRange[1] : null
    }
    
    const response = await fetchQsMediaIncome(params)
    qsReportList.value = response
    pagination.total = response.length
  } catch (error) {
    console.error('加载清算收入报表数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  pagination.currentPage = 1
  loadQsReportData()
}

// 重置搜索表单
const handleReset = () => {
  searchForm.dateRange = getYesterdayDateRange() // 重置为昨天的时间范围
  searchForm.mediaIds = [] // 重置媒体选择
  pagination.currentPage = 1
  loadQsReportData()
}

// 分页大小改变
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  loadQsReportData()
}

// 当前页改变
const handleCurrentChange = (page: number) => {
  pagination.currentPage = page
  loadQsReportData()
}

onMounted(async () => {
  // 加载媒体选项数据
  await loadMediaOptions()
  
  // 加载清算收入报表数据
  await loadQsReportData()
})
// 计算合计数据
const calculateTotal = () => {
  const totals = {
    income: 0,
    realIncome: 0,
    profit: 0
  }
  
  qsReportList.value.forEach(item => {
    totals.income += item.income || 0
    totals.realIncome += item.realIncome || 0
    totals.profit += item.profit || 0
  })
  
  return totals
}

// 表格合计行计算方法
const getSummaries = (param: any) => {
  const { columns, data } = param
  const sums: string[] = []
  const totals = calculateTotal()
  
  columns.forEach((column: any, index: number) => {
    if (index === 0) {
      sums[index] = '合计'
      return
    }
    
    const prop = column.property
    switch (prop) {
      case 'income':
        sums[index] = (totals.income / 100).toFixed(2) + '元'
        break
      case 'realIncome':
        sums[index] = (totals.realIncome / 100).toFixed(2) + '元'
        break
      case 'profit':
        sums[index] = (totals.profit / 100).toFixed(2) + '元'
        break
      default:
        sums[index] = ''
        break
    }
  })
  
  return sums
}
</script>

<style scoped>
.media-report-container {
  padding: 20px;
  min-height: calc(100vh - 60px); /* 减去顶部导航栏高度 */
  background-color: #f5f5f5;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
}

.header-actions {
  display: flex;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 按钮样式 */
:deep(.el-button) {
  border-radius: 8px;
  transition: all 0.3s ease;
  font-weight: 500;
}

:deep(.el-button--primary) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
}

:deep(.el-button--primary:hover) {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(102, 126, 234, 0.4);
  animation: pulse 1.5s infinite;
}

:deep(.el-button--default:hover) {
  transform: translateY(-1px);
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

/* 表单元素样式 */
:deep(.el-form-item) {
  margin-bottom: 16px;
  margin-right: 16px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #2c3e50;
}

:deep(.el-input__wrapper),
:deep(.el-select__wrapper) {
  border-radius: 8px;
  border: 1px solid rgba(102, 126, 234, 0.2);
  background: rgba(255, 255, 255, 0.8);
  transition: all 0.3s ease;
}

:deep(.el-input__wrapper:hover),
:deep(.el-select__wrapper:hover) {
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

:deep(.el-input__wrapper.is-focus) {
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
  transform: translateY(-1px);
  background: rgba(255, 255, 255, 0.95);
}

:deep(.el-date-editor) {
  border-radius: 8px;
  border: 1px solid rgba(102, 126, 234, 0.2);
  background: rgba(255, 255, 255, 0.8);
  transition: all 0.3s ease;
}

:deep(.el-date-editor:hover) {
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

/* 按钮间距 */
:deep(.el-button) {
  margin-left: 8px;
}

/* 卡片圆角 */
:deep(.el-card) {
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

/* 表格圆角 */
:deep(.el-table) {
  border-radius: 12px;
  overflow: hidden;
}

/* 表头样式 */
:deep(.el-table__header-wrapper) {
  border-radius: 12px 12px 0 0;
  overflow: hidden;
}

:deep(.el-table__header) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

:deep(.el-table th) {
  background: transparent;
  color: #ffffff;
  font-weight: 600;
}

:deep(.el-table th.el-table__cell) {
  background: transparent;
}

/* 卡片标题样式 */
.card-header {
  font-weight: 600;
  color: #2c3e50;
  font-size: 16px;
}

/* 分页样式 */
:deep(.el-pagination) {
  justify-content: center;
  margin-top: 24px;
}

:deep(.el-pagination__total),
:deep(.el-pagination__sizes),
:deep(.el-pagination__jump) {
  color: #2c3e50;
  font-weight: 500;
}

/* 玻璃拟态效果 */
.search-card,
.table-card {
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.3);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

/* 动画效果 */
@keyframes pulse {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.05);
  }
  100% {
    transform: scale(1);
  }
}

@keyframes slideInUp {
  from {
    transform: translateY(30px);
    opacity: 0;
  }
  to {
    transform: translateY(0);
    opacity: 1;
  }
}

.search-card {
  animation: slideInUp 0.6s ease-out;
}

.table-card {
  animation: slideInUp 0.8s ease-out;
}

/* 合计行样式 */
.total-row {
  background-color: #f0f9ff !important;
  font-weight: bold;
}

.total-row td {
  text-align: center;
  font-weight: bold;
  background-color: #f0f9ff !important;
}

.hot-media-list {
  max-height: 350px;
  overflow-y: auto;
}

.hot-media-item {
  display: flex;
  align-items: center;
  padding: 15px 0;
  border-bottom: 1px solid #f0f0f0;
}

.hot-media-item:last-child {
  border-bottom: none;
}

.rank-number {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  color: white;
  margin-right: 15px;
}

.rank-top1 {
  background-color: #ffd700;
}

.rank-top2 {
  background-color: #c0c0c0;
}

.rank-top3 {
  background-color: #cd7f32;
}

.rank-normal {
  background-color: #909399;
}

.media-info {
  flex: 1;
}

.media-name {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 5px;
}

.media-stats {
  font-size: 12px;
  color: #909399;
}

.media-stats span {
  margin-right: 15px;
}

.media-type {
  margin-left: 15px;
}
</style>